

using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Abp.Linq;
using Abp.Linq.Extensions;
using Abp.Extensions;
using Abp.UI;
using Abp.Domain.Repositories;
using Abp.Domain.Services;

using Yozeev;
using Yozeev.BusinessLogic;
using Abp.Domain.Entities.Auditing;
using Yozeev.SystemConfig;
using Yozeev.UserManagerment.Users;
using Yozeev.Help;

namespace Yozeev.BusinessLogic.DomainService
{
    /// <summary>
    /// Account领域层的业务管理
    ///</summary>
    public class AccountManager : CommonDomainService, IAccountManager
    {

		private readonly IRepository<Account, Guid> _repository;
		private readonly IRepository<Activity, Guid> _activityRepository;
		private readonly IRepository<ActivityDetail, Guid> _activityDetailRepository;
		private readonly IRepository<AccountDetail, Guid> _accountDetailRepository;

		/// <summary>
		/// Account的构造方法
		///</summary>
		public AccountManager(
			IRepository<Account, Guid> repository
			, IRepository<BranchUser, Guid> branchUserRepository
			, IRepository<Customer, Guid> customerRepository
			, IRepository<Ticket, Guid> ticketRepository
			, IRepository<TicketDetail, Guid> ticketDetailRepository
			, IRepository<Activity, Guid> activityRepository
			, IRepository<ActivityDetail, Guid> activityDetailRepository
			, IRepository<AccountDetail, Guid> accountDetailRepository
		) :base(branchUserRepository, customerRepository, ticketRepository, ticketDetailRepository)
		{
			_repository =  repository;
			_activityRepository = activityRepository;
			_activityDetailRepository = activityDetailRepository;
			_accountDetailRepository = accountDetailRepository;
		}


		/// <summary>
		/// 初始化
		///</summary>
		public void InitAccount()
		{
			throw new NotImplementedException();
		}

		// TODO:编写领域业务代码
		/// <summary>
		/// 结账
		/// </summary>
		/// <param name="activityList">订单列表</param>
		/// <param name="userId">创建人</param>
		public bool SettleAccount(List<Activity> activityList,long userId,string remark="")
		{
			var createBranch = GetBranchUser(userId);
			//根据机构分组
			var listByBranch = activityList.GroupBy(m => new { m.BranchId, m.PayMethodId }).ToList();
			listByBranch.ForEach(ga => {
				var aList = ga.ToList();
				//账单赋值
				var account = new Account
				{
					Id = Guid.NewGuid(),
					AccountNo = CommonHelp.getVoucherNo(),
					BranchId = ga.Key.BranchId,//机构ID
					AccountDate = DateTime.Now.Date,
					Quantity = aList.Where(a => a.TotalQuantity > 0).Sum(a => a.TotalQuantity),
					Amount = aList.Where(a => a.TotalAmount > 0).Sum(a => a.TotalAmount),
					AccountStatus = AccountStatusEnum.NotAccount,
					Remark = remark,
					PayMethodId = ga.Key.PayMethodId,
					RQuantity = aList.Where(a => a.TotalQuantity < 0).Sum(a => a.TotalQuantity),
					RAmount = aList.Where(a => a.TotalAmount < 0).Sum(a => a.TotalAmount),
					TotalQuantity = aList.Sum(a => a.TotalQuantity),
					TotalAmount = aList.Sum(a => a.TotalAmount),
				};
				CommonHelp.SetBranchId(account, createBranch);
				_repository.Insert(account);
				//创建账单明细列表
				List<AccountDetail> accountDetailList = new List<AccountDetail>();
				aList.ForEach(activity => {
					//订单账单关联
					activity.AccountsId = account.Id;
					//订单关闭
					activity.Closed = true;
					//更新订单
					_activityRepository.Update(activity);
					//创建账单明细
					var activityDetailList = _activityDetailRepository.GetAll().Where(m => m.ActivityId == activity.Id).ToList();
					activityDetailList.ForEach(activityDetail=> {
						var accountDetail = new AccountDetail()
						{
                            Id = Guid.NewGuid(),
							AccountId = account.Id,
							ActivityDetailId = activityDetail.Id,
						};
						CommonHelp.SetBranchId(accountDetail, createBranch);
						_accountDetailRepository.Insert(accountDetail);
                        //更新订单明细
                        activityDetail.AccountDetailId = accountDetail.Id;
                        activityDetail.AccountId = account.Id;
                        _activityDetailRepository.Update(activityDetail);

                    });
				});
			});
			return true;
		}
		public bool RSettleAccount(List<Account> accountList, long userId)
		{
			var createBranch = GetBranchUser(userId);
			accountList.ForEach(account => {
				//查询出对应的账单明细
				var accountDetailList = _activityDetailRepository.GetAll().Where(t => t.ActivityId == account.Id).ToList();
				accountDetailList.ForEach(accountDetail => {
					//删除账单明细
					_activityDetailRepository.Delete(accountDetail);
				});
				//查询出对应的订单
				var activityList = _activityRepository.GetAll().Where(t => t.AccountsId == account.Id).ToList();
				activityList.ForEach(activity => {
					activity.AccountsId = null;
					activity.Closed = false;
					_activityRepository.Update(activity);
				});
				//删除账单
				_repository.Delete(account);
			});
			return true;
		}
		/// <summary>
		/// 收款
		/// </summary>
		/// <param name="accountList">账单列表</param>
		/// <param name="userId">收款人Id</param>
		/// <returns></returns>
		public bool CollectAccounts(List<Account> accountList, long userId)
		{
			var createBranch = GetBranchUser(userId);
			accountList.ForEach(account => {
				account.CollectionTime = DateTime.Now;
				account.CollectiorId = userId;
				account.AccountStatus = AccountStatusEnum.IsAccount;
				_repository.Update(account);
			});
			return true;
		}
		/// <summary>
		/// 取消收款
		/// </summary>
		/// <param name="accountList">账单列表</param>
		/// <param name="userId">收款人Id</param>
		/// <returns></returns>
		public bool RCollectAccounts(List<Account> accountList, long userId)
		{
			var createBranch = GetBranchUser(userId);
			accountList.ForEach(account => {
				account.CollectionTime = null;
				account.CollectiorId = null;
				account.AccountStatus = AccountStatusEnum.NotAccount;
				_repository.Update(account);
			});
			return true;
		}

		/// <summary>
		/// 根据Id数组查询账单列表
		/// </summary>
		/// <param name="guids">Id数组</param>
		/// <returns></returns>
		public List<Account> GetAccountListByIds(Guid[] guids)
		{
			var query = _repository.GetAll();
			var entityList = query.Where(m => guids.Contains(m.Id)).ToList();
			return entityList;
		}



	}
}
